import { Service } from '../types/index.js';
import { deepMerge } from '../utils/helpers.js';

/**
 * 路由服务
 * 负责路由配置、动态路由生成、路由权限控制等功能
 */
class RouterService extends Service {
  constructor(container) {
    super(container);
    this.routerConfig = container.getConfig('admin.router');
    this.authService = null;
    this.router = null;
    this.routes = [];
    this.asyncRoutes = [];
    this.menuRoutes = [];
    this.basicRoutes = [];
    
    // 初始化基础路由
    this.initBasicRoutes();
  }

  /**
   * 初始化基础路由
   */
  initBasicRoutes() {
    this.basicRoutes = [
      {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: {
          requiresAuth: false,
          hidden: true
        }
      },
      {
        path: '/404',
        name: 'NotFound',
        component: () => import('@/views/Error/404.vue'),
        meta: {
          requiresAuth: false,
          hidden: true
        }
      },
      {
        path: '/403',
        name: 'Forbidden',
        component: () => import('@/views/Error/403.vue'),
        meta: {
          requiresAuth: false,
          hidden: true
        }
      },
      {
        path: '/',
        redirect: '/dashboard',
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: {
          requiresAuth: true,
          title: 'Dashboard',
          icon: 'dashboard'
        }
      }
    ];
    
    this.routes = [...this.basicRoutes];
  }

  /**
   * 初始化路由服务
   */
  init(router) {
    this.router = router;
    this.authService = this.container.get('auth');
    
    // 应用路由守卫
    this.applyRouteGuards();
  }

  /**
   * 应用路由守卫
   */
  applyRouteGuards() {
    if (!this.router || !this.authService) return;
    
    const { beforeEach } = this.authService.getRouteGuard();
    this.router.beforeEach((to, from, next) => {
      // 调用认证服务的前置守卫
      beforeEach(to, from, next);
    });
  }

  /**
   * 注册动态路由
   */
  registerAsyncRoutes(routes) {
    this.asyncRoutes = [...routes];
    this.generateMenuRoutes();
  }

  /**
   * 根据权限生成可访问路由
   */
  generateAccessibleRoutes() {
    if (!this.authService) return [];
    
    const filterRoutesByPermission = (routes) => {
      return routes.filter(route => {
        // 检查路由权限
        if (route.meta && route.meta.permission && !this.authService.hasPermission(route.meta.permission)) {
          return false;
        }
        
        // 检查角色权限
        if (route.meta && route.meta.role && !this.authService.hasRole(route.meta.role)) {
          return false;
        }
        
        // 递归过滤子路由
        if (route.children && route.children.length) {
          route.children = filterRoutesByPermission(route.children);
          return route.children.length > 0;
        }
        
        return true;
      });
    };
    
    return filterRoutesByPermission([...this.asyncRoutes]);
  }

  /**
   * 生成菜单路由
   */
  generateMenuRoutes() {
    const accessibleRoutes = this.generateAccessibleRoutes();
    
    const filterMenuRoutes = (routes) => {
      return routes.filter(route => {
        // 排除隐藏的路由
        if (route.meta && route.meta.hidden === true) {
          return false;
        }
        
        // 递归处理子菜单
        if (route.children && route.children.length) {
          route.children = filterMenuRoutes(route.children);
          // 如果子菜单过滤后为空，则不显示该菜单项
          return route.children.length > 0;
        }
        
        return true;
      });
    };
    
    this.menuRoutes = filterMenuRoutes([...this.basicRoutes, ...accessibleRoutes]);
    return this.menuRoutes;
  }

  /**
   * 获取菜单路由
   */
  getMenuRoutes() {
    return this.menuRoutes;
  }

  /**
   * 获取当前路由的面包屑
   */
  getBreadcrumb(currentRoute) {
    const breadcrumbList = [];
    
    if (!currentRoute) return breadcrumbList;
    
    // 构建面包屑路径
    const buildBreadcrumb = (route, parentPath = '') => {
      const path = parentPath ? `${parentPath}/${route.path}` : route.path;
      
      breadcrumbList.push({
        path,
        name: route.name,
        title: route.meta?.title || route.name,
        icon: route.meta?.icon
      });
      
      // 如果有子路由且正在访问，则继续构建
      if (route.children && route.children.length) {
        const matchedChild = route.children.find(child => 
          currentRoute.path.startsWith(`${path}/${child.path}`) || currentRoute.path === path
        );
        if (matchedChild) {
          buildBreadcrumb(matchedChild, path);
        }
      }
    };
    
    // 从根路由开始构建
    const rootRoute = this.menuRoutes.find(route => 
      currentRoute.path.startsWith(route.path) || currentRoute.path === route.path
    );
    
    if (rootRoute) {
      buildBreadcrumb(rootRoute);
    }
    
    return breadcrumbList;
  }

  /**
   * 根据路径查找路由
   */
  findRouteByPath(path) {
    const findRoute = (routes) => {
      for (const route of routes) {
        if (route.path === path) {
          return route;
        }
        if (route.children && route.children.length) {
          const found = findRoute(route.children);
          if (found) return found;
        }
      }
      return null;
    };
    
    return findRoute([...this.routes, ...this.asyncRoutes]);
  }

  /**
   * 根据名称查找路由
   */
  findRouteByName(name) {
    const findRoute = (routes) => {
      for (const route of routes) {
        if (route.name === name) {
          return route;
        }
        if (route.children && route.children.length) {
          const found = findRoute(route.children);
          if (found) return found;
        }
      }
      return null;
    };
    
    return findRoute([...this.routes, ...this.asyncRoutes]);
  }

  /**
   * 刷新当前路由
   */
  refreshCurrentRoute() {
    if (!this.router) return;
    
    const currentRoute = this.router.currentRoute.value;
    this.router.replace({
      path: '/redirect' + currentRoute.path
    });
  }

  /**
   * 重置路由
   */
  resetRoutes() {
    if (!this.router) return;
    
    // 清除所有动态路由
    this.asyncRoutes.forEach(route => {
      if (route.name) {
        this.router.removeRoute(route.name);
      }
    });
    
    // 重新添加基础路由
    this.routes = [...this.basicRoutes];
    this.menuRoutes = [];
    this.asyncRoutes = [];
  }

  /**
   * 动态添加路由
   */
  addRoute(route) {
    if (!this.router) return false;
    
    try {
      this.router.addRoute(route);
      this.asyncRoutes.push(route);
      this.generateMenuRoutes();
      return true;
    } catch (error) {
      console.error('Failed to add route:', error);
      return false;
    }
  }

  /**
   * 动态添加路由到指定父路由
   */
  addRouteToParent(parentName, route) {
    if (!this.router || !parentName) return false;
    
    try {
      this.router.addRoute(parentName, route);
      
      // 更新asyncRoutes中的对应父路由
      const updateChildRoute = (routes) => {
        for (let i = 0; i < routes.length; i++) {
          if (routes[i].name === parentName) {
            if (!routes[i].children) {
              routes[i].children = [];
            }
            routes[i].children.push(route);
            return true;
          }
          if (routes[i].children && routes[i].children.length) {
            if (updateChildRoute(routes[i].children)) {
              return true;
            }
          }
        }
        return false;
      };
      
      updateChildRoute(this.asyncRoutes);
      this.generateMenuRoutes();
      return true;
    } catch (error) {
      console.error('Failed to add child route:', error);
      return false;
    }
  }

  /**
   * 启动服务
   */
  boot() {
    console.log('RouterService booted');
    
    // 监听用户登录状态变化，重新生成菜单
    this.authService.on('loginSuccess', () => {
      this.generateMenuRoutes();
    });
    
    this.authService.on('logoutSuccess', () => {
      this.resetRoutes();
    });
  }

  /**
   * 关闭服务
   */
  shutdown() {
    console.log('RouterService shutdown');
    this.resetRoutes();
  }
}

export default RouterService;